"use strict";

/**
 * @import * as rspack from "@rspack/core";
 * @import * as webpack  from "webpack";
 */
const HtmlRspackPlugin = require("html-rspack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

/**
 * TODO: Option
 * @implements {rspack.RspackPluginInstance}
 */
class HtmlRspackPatchPlugin {
  /**
   * @param {[from: string | RegExp,to: string][]} replaceEntry
   */
  constructor(replaceEntry) {
    this.replaceString = replaceEntry;
  }

  static NAME = "HtmlRspackPatchPlugin";

  /**
   * @param {rspack.Compiler} compiler
   * @returns {void}
   */
  apply(compiler) {
    compiler.hooks.compilation.tap(
      HtmlRspackPatchPlugin.NAME,
      (compilation) => {
        // HtmlRspackPlugin.getCompilationHooks(
        //   compilation,
        // ).beforeAssetTagGeneration.tap(HtmlRspackPatchPlugin.NAME, (data) => {
        //   data.assets.favicon = "favicon.rspack.png";
        //   return data;
        // });
        HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tap(
          HtmlRspackPatchPlugin.NAME,
          (data) => {
            for (const [from, to] of this.replaceString) {
              data.html = data.html.replace(from, to);
            }
            return data;
          },
        );
      },
    );
  }
}

/**
 * TODO: Option
 * @implements {webpack.WebpackPluginInstance}
 */
class HtmlWebpackPatchPlugin {
  /**
   * @param {[from: string | RegExp,to: string][]} replaceEntry
   */
  constructor(replaceEntry) {
    this.replaceString = replaceEntry;
  }

  static NAME = "HtmlWebpackPatchPlugin";

  /**
   * @param {webpack.Compiler} compiler
   * @returns {void}
   */
  apply(compiler) {
    compiler.hooks.compilation.tap(
      HtmlRspackPatchPlugin.NAME,
      (compilation) => {
        // HtmlRspackPlugin.getCompilationHooks(
        //   compilation,
        // ).beforeAssetTagGeneration.tap(HtmlRspackPatchPlugin.NAME, (data) => {
        //   data.assets.favicon = "favicon.rspack.png";
        //   return data;
        // });
        HtmlWebpackPlugin.getCompilationHooks(compilation).beforeEmit.tap(
          HtmlRspackPatchPlugin.NAME,
          (data) => {
            for (const [from, to] of this.replaceString) {
              data.html = data.html.replace(from, to);
            }
            return data;
          },
        );
      },
    );
  }
}

module.exports = {
  HtmlRspackPatchPlugin,
  HtmlWebpackPatchPlugin,
};
